package com.nightwalkbuddy.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.nightwalkbuddy.dto.User;

/**
 * SQLite implementation for saving user in db
 * 
 * @author htisabel
 * 
 */
public class UserProviderStub extends SQLiteOpenHelper implements IUserDAO {

	User user = new User();
	// SQLite db
	private static final String DB_NAME = "nightwalkUsers.db";
	private static final String TABLE_NAME = "nightwalkUser";
	private static final int DB_VERSION = 1;
	private static final String _ID = "userid", USERNAME = "username",
			PASSWORD = "password", EM_PHONE_NR = "EmPhoneNr", EM_MSG = "EmMsg";
	private static final String CREATE_DB = "CREATE TABLE " + TABLE_NAME + "("
			+ _ID + " INTEGER PRIMARY KEY," + USERNAME + " TEXT NOT NULL,"
			+ PASSWORD + " TEXT NOT NULL," + EM_PHONE_NR + " TEXT NOT NULL,"
			+ EM_MSG + " TEXT NOT NULL);";
	private static final String COUNT_RECORD = "SELECT COUNT(*) FROM "
			+ TABLE_NAME;
	private static final String UPGRADE_MSG = "DB upgraded, old data destroyed. New version: ";
	private static final String FETCH_ERROR = "user not found in db";
	private static final String DB_DUMMY = "dummyUser";
	private static final String DUMMY_PHONE = "5556";

	/**
	 * constructor
	 * 
	 * @param context
	 *            the context where UserProviderLive is initiated. Used for
	 *            SQLiteOpenHelper super class
	 */
	public UserProviderStub(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(CREATE_DB);
		// place a dummy user to create SQLite db
		ContentValues values = new ContentValues();
		values.put(USERNAME, DB_DUMMY); // username
		values.put(PASSWORD, DB_DUMMY); // password
		values.put(EM_PHONE_NR, DUMMY_PHONE); // emergency contact phoneNr
		values.put(EM_MSG, DB_DUMMY); // emergency text msg
		db.insert(TABLE_NAME, null, values);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.w(UserProviderStub.class.getName(), UPGRADE_MSG + newVersion);
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
		onCreate(db);
	}

	@Override
	public void save(User user) throws Exception {
		SQLiteDatabase db = this.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(USERNAME, user.getUsername()); // username
		values.put(PASSWORD, user.getPassword()); // password
		values.put(EM_PHONE_NR, user.getEmPhoneNr()); // emergency contact
														// phoneNr
		values.put(EM_MSG, user.getEmMsg()); // emergency text msg

		/**
		 * First time using NightwalkBuddy, it will create new user's db record
		 * After that, it will regularly update the record using info fetched
		 * from the Web site in case emergency contact info changes. However,
		 * unlike the Web MySQL where the password is encrypted, SQLite data
		 * here is not encrypted.
		 */
		try {
			Cursor cursor;
			cursor = db.rawQuery(COUNT_RECORD, null);
			if (cursor.getCount() > 1) {
				db.update(TABLE_NAME, values, USERNAME + "=?",
						new String[] { user.getUsername() });
			} else {
				db.insert(TABLE_NAME, null, values);
			}
		} catch (SQLiteException e) {
			long id = db.insert(TABLE_NAME, null, values);
			Log.w(TABLE_NAME, String.valueOf(id));
		}

		db.close();
	}

	@Override
	public User fetch(String username) throws Exception {
		SQLiteDatabase db = this.getReadableDatabase();
		User u = new User();
		Cursor cursor = db.query(TABLE_NAME, new String[] { USERNAME, PASSWORD,
				EM_PHONE_NR, EM_MSG }, USERNAME + "=?",
				new String[] { username }, null, null, null, null);
		try {
			if (cursor != null) {
				cursor.moveToFirst();

				u.setUsername(username);
				u.setPassword(cursor.getString(1));
				u.setEmPhoneNr(cursor.getString(2));
				u.setEmMsg(cursor.getString(3));
			} else {
				Log.e(TABLE_NAME, FETCH_ERROR);
			}
		} catch (SQLiteException e) {
			Log.w(TABLE_NAME, e.toString());
		}
		db.close();
		return u;
	}

}
